package xcu.lxj.nettychat.websocket.netty;

import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * @Author XinJian Lei
 * @Date 2024/9/15 16:33
 * @Version 1.0
 */
@Slf4j
public class HttpHeaderHandler extends ChannelInboundHandlerAdapter {




    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)  {

        if(msg instanceof FullHttpRequest request){
            // 把 msg 转发成 FullHttpRequest 对象
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(request.uri());
            
            // 获取token参数
            String token = Optional.ofNullable(urlBuilder.getQuery()).map(k->k.get("token")).map(CharSequence::toString).orElse("");
            if(StringUtil.isEmpty(token)){
                log.warn("token为空");
                ctx.channel().close();
            }
            else {
//                log.info("token = {}",token);
                NettyAttrUtils.setAttr(ctx.channel(),NettyAttrUtils.TOKEN,token);
            }
            //重新组合 url 否则 有请求参数无法成功握手
            request.setUri(urlBuilder.getPath().toString());
            // 一个方法执行一次这个通道
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(request);
        }else {
            ctx.fireChannelRead(msg);
        }

    }
}
